package cn.lingyangwl.agile.plugin.file.preview.service.impl;

import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.response.RetOps;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.plugin.file.preview.model.FileAttribute;
import cn.lingyangwl.agile.plugin.file.preview.model.FilePreviewRS;
import cn.lingyangwl.agile.plugin.file.preview.service.FileHandlerService;
import cn.lingyangwl.agile.plugin.file.preview.service.FilePreview;
import cn.lingyangwl.agile.plugin.file.preview.utils.AppFileUtils;
import cn.lingyangwl.agile.plugin.file.preview.utils.DownloadUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片文件处理
 *
 * @author shenguangyang
 * @since 1.0.0
 */
@Service
public class PictureFilePreviewImpl implements FilePreview {

    private final FileHandlerService fileHandlerService;
    private final OtherFilePreviewImpl otherFilePreview;

    public PictureFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) {
        this.fileHandlerService = fileHandlerService;
        this.otherFilePreview = otherFilePreview;
    }

    @Override
    public FilePreviewRS filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
        url= AppFileUtils.htmlEscape(url);
        List<String> imgUrls = new ArrayList<>();
        imgUrls.add(url);
        String fileKey = fileAttribute.getFileKey();
        List<String> zipImgUrls = fileHandlerService.getImgCache(fileKey);
        if (!CollectionUtils.isEmpty(zipImgUrls)) {
            imgUrls.addAll(zipImgUrls);
        }
        // 不是http开头，浏览器不能直接访问，需下载到本地
        if (url != null && !url.toLowerCase().startsWith("http")) {
            Resp<String> response = DownloadUtils.downLoad(fileAttribute, null);
            if (!RetOps.of(response).isSuccess()) {
                throw new BizException(response.getMsg());
            } else {
                String file = fileHandlerService.getRelativePath(response.getData());
                imgUrls.clear();
                imgUrls.add(file);
                model.addAttribute("imgUrls", imgUrls);
                model.addAttribute("currentUrl", file);
            }
        } else {
            model.addAttribute("imgUrls", imgUrls);
            model.addAttribute("currentUrl", url);
        }
        return FilePreviewRS.builder().type(PICTURE_FILE_PREVIEW_PAGE).build();
    }
}
